// web/src/components/auth/login-form.tsx
'use client';
import React, {useState, useTransition} from 'react';
import CardWrapper from "@/components/auth/card-wrapper";
// 如果没用client, 报错xxx is not a function
import {useForm} from "react-hook-form";
import * as z from 'zod'
import {LoginSchema} from "@/schemas";
import {zodResolver} from "@hookform/resolvers/zod";
import {Form, FormControl, FormField, FormItem, FormLabel, FormMessage} from "@/components/ui/form";
import {Input} from "@/components/ui/input";
import {Button} from "@/components/ui/button";
import FormError from "@/components/form-error";
import FormSuccess from "@/components/form-success";
import {login} from "@/actions/login";
import {useRouter, useSearchParams} from "next/navigation";
import Link from "next/link";

const LoginForm = () => {
    const searchParams = useSearchParams()
    const urlError = searchParams.get('error') === 'OAuthAccountNotLinked'
        ? "Email already in use with different provider" : ""

    // 显示双因素验证相关
    const [showTwoFactor, setShowTwoFactor] = useState(false);
    // 提交表单后的错误或成功信息
    const [error, setError] = useState<string | undefined>('')
    const [success, setSuccess] = useState<string | undefined>('')

    const [isPending, startTransition] = useTransition()

    const form = useForm<z.infer<typeof LoginSchema>>({
        resolver: zodResolver(LoginSchema),
        defaultValues: {
            email: '',
            password: ''
        }
    })

    const onSubmit = (values: z.infer<typeof LoginSchema>) => {
        setError('')
        setSuccess('')

        // 可以获取是否执行中的状态
        startTransition(() => {
            login(values)
                .then((data) => {
                    if (data?.error) {
                        form.reset()
                        setError(data.error)
                    }
                    if (data?.success) {
                        form.reset()
                        setSuccess(data.success)
                    }
                    if (data?.twoFactor) {
                        setShowTwoFactor(true)
                    }
                })
                .catch(() => setError('Something went wrong!'))
        })
    }

    return (
        <CardWrapper
            headerLabel={'Welcome back'}
            backButtonLabel={`Don't have an account?`}
            backButtonHref={`/auth/register`}
            showSocial
        >
            <Form {...form}>
                <form
                    onSubmit={form.handleSubmit(() => {
                        onSubmit(form.getValues())
                    })}
                    className="space-y-6"
                >
                    <div className={`space-y-4`}>
                        {showTwoFactor && (
                            <FormField
                                control={form.control}
                                name="code"
                                render={({field}) => (
                                    <FormItem>
                                        <FormLabel>Two Factor Code</FormLabel>
                                        <FormControl>
                                            <Input
                                                {...field}
                                                disabled={isPending}
                                                placeholder="2FactorAuthToken"
                                            />
                                        </FormControl>
                                        <FormMessage/>
                                    </FormItem>
                                )}
                            />
                        )}
                        {!showTwoFactor &&
                            <>
                                <FormField
                                    control={form.control}
                                    name="email"
                                    render={({field}) => (
                                        <FormItem>
                                            <FormLabel>Email</FormLabel>
                                            <FormControl>
                                                <Input
                                                    {...field}
                                                    disabled={isPending}
                                                    placeholder="Email"
                                                    type="email"
                                                />
                                            </FormControl>
                                            <FormMessage/>
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="password"
                                    render={({field}) => (
                                        <FormItem>
                                            <FormLabel>Password</FormLabel>
                                            <FormControl>
                                                <Input
                                                    {...field}
                                                    disabled={isPending}
                                                    placeholder="******"
                                                    type="password"
                                                />
                                            </FormControl>
                                            <FormMessage/>
                                            <Button
                                                size={'sm'}
                                                variant={'link'}
                                                asChild
                                                className={`px-0 font-normal`}
                                            >
                                                <Link href={`/auth/reset`}>
                                                    Forgot password?
                                                </Link>
                                            </Button>
                                        </FormItem>
                                    )}
                                />
                            </>
                        }
                    </div>
                    <FormError message={error || urlError}/>
                    <FormSuccess message={success}/>
                    <Button
                        type="submit"
                        disabled={isPending}
                        className={`w-full`}
                    >
                        {showTwoFactor ? 'Confirm' : 'Login'}
                    </Button>
                </form>
            </Form>
        </CardWrapper>
    );
};

export default LoginForm;